<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;
use app\common\service\User as UserService;
use app\common\model\UserMoneyLog as MoneyLogModel;

/**
 * 订单支付回调成功时调用此类
 */
class OrderQuery Extends Model
{
    private $UserService;
    private $MoneyLogModel;
    public function __construct()
    {
        parent::__construct();
        $this->UserService =  new UserService();
        $this->MoneyLogModel =  new MoneyLogModel();

    }

    /**
     *  通过支付用户id进行分润奖励操作
     * @param array $oderArray 传递参数数组
     * @return bool            返回true或者false
     */
    public function orderDispose($oderArray=array()){
        Db::startTrans();
        try{
          //检查粉丝（支付用户id）的直属上级是否是上商家,如果是商家返回false不是返true
          $isParentShop=$this->UserService->getIsParentIdShop($oderArray['user_id'],$oderArray['shop_user_id']);
          if($isParentShop){
              //粉丝直属上级商家（直属）
              $getParentShop=$this->UserService->getParentShopAgent($oderArray['user_id']);

              //购买商家上级及上上级用户获取.
              $UsershopParent=$this->UserService->getShopAgentList($oderArray['shop_user_id']);

              $userMoney=array(
                  'money'=>0,
                  'before'=>0,
                  'after'=>0,
                  'memo'=>'',
                  'createtime'=>time(),
                  'shoporder_id'=>$oderArray['order_id'],
                  'money_type'=>0
              );

              //直属商家分润返比例
              if(!empty($getParentShop)){
                  if($getParentShop->consume_res>0){
                      if($getParentShop->consume_res>100){
                          $consume_res=1;
                      }else{
                          $consume_res=$getParentShop->consume_res/100;
                      }
                      $money=$oderArray['money']*$consume_res;
                      $userMoney['money']=round($money,2);
                      $moneyNew=$money+$getParentShop->money;
                      $userMoney['after']=round($moneyNew,2);
                      $userMoney['before']=$getParentShop->money;
                      $userMoney['user_id']=$getParentShop->id;
                      $userMoney['money_type']=13;
                      $userMoney['memo']='跨商家收益';
                      if(!empty($userMoney['money'])){
                          $this->MoneyLogModel->InsertMoneyLog($userMoney,$userMoney['user_id']);
                      }
                  }
              }



              //商家二级分润反比例
              $leval_array=array('上级','上上级');
              if(!empty($UsershopParent)){
                  $UsershopParent=collection($UsershopParent)->toArray();
                  foreach ($UsershopParent as  $key=>$val){
                      if($val['consume_res']>0){
                          if($val['consume_res']>100){
                              $consume_res=1;
                          }else{
                              $consume_res=$val['consume_res']/100;
                          }
                          $money=$oderArray['money']*$consume_res;
                          $userMoney['money']=round($money,2);
                          $userMoney['after']=round(($money+$val['money']),2);
                          $userMoney['before']=$val['money'];
                          $userMoney['user_id']=$val['id'];
                          $userMoney['money_type']=1;
                          $userMoney['memo']=$leval_array[$key].'二级个权分润';
                          $userMoney['createtime']=time();
                          if(!empty($userMoney['money'])){
                              $this->MoneyLogModel->InsertMoneyLog($userMoney,$val['id']);
                          }
                      }
                  }
              }


          }

            //服务区代理
            $SeviceProxy=$this->UserService->getServiceProxy($oderArray['shop_id']);

            //商家代理返比例(大区、省代理、市代理、区代理)
            if(!empty($SeviceProxy)){
                $SeviceProxy=collection($SeviceProxy)->toArray();
                $userMoney['shoporder_id']=$oderArray['order_id'];
                foreach ($SeviceProxy as  $val){
                    if($val['consume_res']>0){
                        if($val['consume_res']>100){
                            $consume_res=1;
                        }else{
                            $consume_res=$val['consume_res']/100;
                        }
                        $money=round($oderArray['money']*$consume_res,2);
                        $userMoney['money']=$money;
                        $userMoney['after']=round(($money+$val['money']),2);
                        $userMoney['before']=$val['money'];
                        $userMoney['user_id']=$val['id'];
                        $userMoney['money_type']=3;
                        $userMoney['memo']='服务商分润';
                        $userMoney['createtime']=time();
                        if(!empty($userMoney['money'])){
                            $this->MoneyLogModel->InsertMoneyLog($userMoney,$val['id']);
                        }
                    }
                }
            }

            Db::commit();
        }catch (\Exception $e){
            DB::rollback();
            return false;
        }
        return true;
    }

    /**
     * 自己消费返积分
     * @param array $OrderArray
     * @return bool
     */
    public function  HostIntegration($OrderArray=array()){
        try{
            $UserModel=new User();
            $where['id']=$OrderArray['user_id'];
            $UserFind=$UserModel->where($where)->find();
            if(!empty($UserFind)){
                $UserFind=$UserFind->toArray();
                if($UserFind['integer_res']>0){
                    if($UserFind['integer_res']>100){
                        $integer_res=1;
                    }else{
                        $integer_res=$UserFind['integer_res']/100;
                    }
                    $integral=intval(($OrderArray['play_price']+$OrderArray['remainder'])*$integer_res,2);
                    if($integral>0){
                        $IntegralData['type']=6;
                        $IntegralData['integral']=$integral;
                        $IntegralData['user_id']=$UserFind['id'];
                        $IntegralData['remark']='消费返积分';
                        $IntegralData['createtime']=time();

                        $this->UserService->SetIntegralInsert($IntegralData);
                    }
                }
            }
        }catch (Exception $e){
            return false;
        }
        return true;
    }

    /**
     * 消费者积分返（消费者上级及上上级）
     * @param $OrderArray
     * @return bool
     */
    public function Integration($OrderArray=array()){
        try{
            //消费者上级个权及上上级个权用户获取.
//            $UserAgentParent=$this->UserService->getShopAgentList($OrderArray['user_id']);
            $UserAgentParent=$this->UserService->getParentListUser($OrderArray['user_id']);
            //商家二级分润反比例
            $leval_array=array('上一级','上上级');
            if(!empty($UserAgentParent)){
                $UserAgentParent=collection($UserAgentParent)->toArray();
                foreach ($UserAgentParent as  $key=>$val){
                    if($val['integer_res']>0){
                        if($val['integer_res']>100){
                            $integer_res=1;
                        }else{
                            $integer_res=$val['integer_res']/100;
                        }
                        $integral=intval(($OrderArray['play_price']+$OrderArray['remainder'])*$integer_res,2);
                        if($integral>0){
                            $IntegralData['type']=5;
                            $IntegralData['integral']=$integral;
                            $IntegralData['user_id']=$val['id'];
                            $IntegralData['remark']=$leval_array[$key];
                            $IntegralData['createtime']=time();
                            $this->UserService->SetIntegralInsert($IntegralData);
                        }
                    }
                }
            }
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /**
     * 返贡献值
     * @param array $oderArray  传递订单数组参数
     * @return bool             返回处理结果true或者false
     */
    public function contribution($oderArray=array()){
        Db::startTrans();
        try{
            //返上级个权贡献和返上上级个权贡献值
            $UserParent=$this->UserService->getParentListUser($oderArray['user_id']);
            if(!empty($UserParent)){
                $UserParent=collection($UserParent)->toArray();
                $leval_array=array('上一级','上上级');
                foreach ($UserParent as  $key=>$val){
                    if($val['contribute_res']>0){
                        if($val['contribute_res']>100){
                            $contribute_res=1;
                        }else{
                            $contribute_res=$val['contribute_res']/100;
                        }

                        //计算实际支付金额不包括余额和首单优惠
                        $moneyAll=round(($oderArray['play_price']+$oderArray['remainder'])*$contribute_res,2);
                        $residual_new=$moneyAll;
                        $residual_array=explode('.',$residual_new);
                        if(!empty($residual_array[0])){
                            $score=$residual_array[0]+$val['score'];
                            $residual_new=$residual_array[0];
                        }else{
                            $residual_new=0;
                            $score=$val['score'];
                        }
                        if(!empty($residual_array[1])){
                            $residual_yu=$residual_array[1];
                        }else{
                            $residual_yu=0;
                        }
                        $residual_new=round($residual_new,2);
                        $userMoney['money']=$residual_new;
                        $userMoney['before']=$val['score'];
                        $userMoney['after']=$score;
                        $userMoney['user_id']=$val['id'];
                        $userMoney['money_type']=8;
                        $userMoney['createtime']=time();
                        $userMoney['memo']='二级贡献值';
                        $userMoney[ 'shoporder_id']=$oderArray['order_id'];
                        if(!empty($userMoney['money'])){
                            $this->MoneyLogModel->SetCore($userMoney,$residual_yu);
                        }
                    }
                }
            }
            //自己返贡献值
            $hostUser=Db::name('user')->where(['id'=>$oderArray['user_id']])->find();

            if(!empty($hostUser)){
                if($hostUser['contribute_res']>0){

                    if($hostUser['contribute_res']>100){
                        $contribute_res=1;
                    }else{
                        $contribute_res=$hostUser['contribute_res']/100;
                    }
                    $moneyAll=round(($oderArray['play_price']+$oderArray['remainder'])*$contribute_res,2);
                    $residual_new=$hostUser['residual']+$moneyAll;
                    $residual_array=explode('.',$residual_new);
                    if(!empty($residual_array[0])){
                        $score=$residual_array[0]+$hostUser['score'];
                        $residual_new=$residual_array[0];
                    }else{
                        $residual_new=0;
                        $score=$hostUser['score'];
                    }
                    if(!empty($residual_array[1])){
                        $residual_yu=$residual_array[1];
                    }else{
                        $residual_yu=0;
                    }
                    $residual_new=round($residual_new,2);


                    $userMoney['money']=$residual_new;
                    $userMoney['before']=$hostUser['score'];
                    $userMoney['after']=$score;
                    $userMoney['user_id']=$hostUser['id'];
                    $userMoney['createtime']=time();
                    $userMoney['memo']='消费贡献值';
                    $userMoney['money_type']=8;
                    $userMoney[ 'shoporder_id']=$oderArray['order_id'];
                    if(!empty($userMoney['money'])){
                        $this->MoneyLogModel->SetCore($userMoney,$residual_yu);
                    }

                }
            }

            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 自己消费
     * @param $oderArray    传递订单信息数组
     * @return bool 执行结果
     */
    public function consumption($oderArray=array()){
        try{
            Db::startTrans();
            if(!empty($oderArray['remainder'])){
                $money=round(($oderArray['remainder']),2);
                $userMoney['money']=$money;
                $userMoney['user_id']=$oderArray['user_id'];
                $userMoney['money_type']=9;
                $userMoney['createtime']=time();
                $userMoney['memo']='消费余额';
                $userMoney[ 'shoporder_id']=$oderArray['order_id'];
                if(!empty( $userMoney['money'])){
                    $this->MoneyLogModel->setMoneyLog($userMoney);
                }
            }
            Db::commit();

            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 自己消费
     * @param $oderArray    传递订单信息数组
     * @return bool 执行结果
     */
    public function consumptionOrderPlay($oderArray=array()){
        try{
            Db::startTrans();

            if(!empty($oderArray['total_price'])){
                $money=round(($oderArray['total_price']),2);
                $userMoney['money']=$money;
                $userMoney['user_id']=$oderArray['user_id'];
                $userMoney['money_type']=12;
                $userMoney['createtime']=time();
                $userMoney['memo']='消费总金额';
                $userMoney[ 'shoporder_id']=$oderArray['order_id'];
                if(!empty( $userMoney['money'])){
                    $this->MoneyLogModel->setMoneyLog($userMoney);
                }
            }
            Db::commit();

            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 商家返货款
     * @param $oderArray 传递订单信息数组
     * @return bool 执行结果
     */
    public function paragraph($oderArray=array()){
        Db::startTrans();
        try{
            $user=Db::name('user')->where(['id'=>$oderArray['shop_user_id']])->find();
            $money=$oderArray['money_new'];
            $money=round($money,2);
            $userMoney['money']=$money;
            $userMoney['before']=$user['money'];
            $userMoney['after']=round(($money+$user['money']),2);
            $userMoney['user_id']=$oderArray['shop_user_id'];
            $userMoney['money_type']=10;
            $userMoney['memo']='货款';
            $userMoney['createtime']=time();
            $userMoney[ 'shoporder_id']=$oderArray['order_id'];
            if(!empty( $userMoney['money'])){
                $this->MoneyLogModel->InsertMoneyLog($userMoney,$oderArray['shop_user_id']);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }

}
